#include "dlinklist.h"

// 初始化一个带头节点的空双向循环链表
dlist init_list()
{
    dlist head = calloc(1, sizeof(dnode));
    if(head != NULL)
    {
        head->prev = head;
        head->next = head;
    }
    return head;
}

dlist add_list(dlist head, dlist newnode)
{
    newnode->prev = head;
    newnode->next = head->next;
    head->next = newnode;
    newnode->next->prev = newnode;
}

dlist add_list_tail(dlist head, dlist newnode)
{
    add_list(head->prev, newnode);
}

// 将p指向的节点从链表中剔除出去
void remove_node(dlist p)
{
    if(p == NULL)
        return;

    p->prev->next = p->next;
    p->next->prev = p->prev;
    p->next = NULL;
    p->prev = NULL;
}

// 将p指向的节点，移动到以head为首的链表的末尾
void move_tail(dlist head, dlist p)
{
    // 先删除
    remove_node(p);
    // 再插入
    add_list_tail(head, p);
}

// 遍历双循环链表
void show(dlist head)
{
    for(dlist p=head->next; p!=head; p=p->next)
        printf("%d\t", p->data);
    printf("\n");
}

void destroy_init(dlist head)
{
}

dlist new_node(int num)
{
    dlist new = calloc(1, sizeof(dnode));
    if(new != NULL)
    {
        new->prev = new;
        new->next = new;
        new->data = num;
    }
    return new;
}